<?php namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\AreaRequest;
use App\Http\Controllers\Controller;
use App\Services\AreaService;
use App\Models\Area;

class AreaController extends Controller
{

    public function getIndex(AreaService $areaService, Request $request)
    {
        return view('admin.area.areas', [
            'request' => $request,
            'areas' => $areaService->getList($request),
        ]);
    }

    public function getAdd()
    {
        return view('admin.area.add', [
            'provinces' => Area::where(['p_id' => 0, 'level' => 1])->get()
        ]);
    }

    public function postAdd(AreaService $areaService, AreaRequest $areaRequest)
    {
        $areaService->create([
            'name' => $areaRequest->input('name'),
            'p_id' => $areaRequest->input('city_id') ?: $areaRequest->input('province_id', 0)
        ]);
        return $this->bSuccess('添加成功', true, ['tabid' => 'areas']);
    }

    public function getEdit($id)
    {
        $area = Area::find($id);
        return view('admin.area.edit', [
            'provinces' => Area::where(['p_id' => 0, 'level' => 1])->get(),
            'cities' => Area::where(['p_id' => $area->level == 3 ? $area->p_area->p_id : $area->p_id, 'level' => 2])->get(),
            'area' => $area
        ]);

    }

    public function postEdit(AreaService $areaService, AreaRequest $areaRequest)
    {
        $areaService->update($areaRequest->input('id'), [
            'name' => $areaRequest->input('name'),
            'p_id' => $areaRequest->input('city_id') ?: $areaRequest->input('province_id', 0)
        ]);
        return $this->bSuccess('修改成功', true, ['tabid' => 'areas']);
    }

    public function getDelete($id, AreaService $areaService)
    {
        $areaService->delete($id);
        return $this->bSuccess('删除成功', false);
    }
}